package com.ysm.smfu.activity;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.ysm.smfu.R;
import com.ysm.smfu.StatusBarCompat;
import com.ysm.smfu.bean.DetailBusinessInfo;
import com.ysm.smfu.protocal.BaseProtocal;
import com.ysm.smfu.protocal.MyStringCallBack;
import com.ysm.smfu.utils.PrintUtil;
import com.ysm.smfu.utils.ToastUtils;
import com.ysm.smfu.utils.UIUtils;
import com.ysm.smfu.view.MyCycleViewPager;
import com.ysm.smfu.view.RecyclerImageView;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionNo;
import com.yanzhenjie.permission.PermissionYes;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;
import com.zhy.autolayout.AutoLinearLayout;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2016/9/21.
 */
public class DetailActivity extends BaseActivity implements ViewPager.OnPageChangeListener {

    @BindView(R.id.largeImg)
    MyCycleViewPager largeImg;
    @BindView(R.id.act_detail_profile)
    TextView actDetailProfile;
    @BindView(R.id.act_detail_smallImg)
    ImageView actDetailSmallImg;
    @BindView(R.id.act_search_name)
    TextView actSearchName;
    @BindView(R.id.act_detail_address_property)
    TextView actDetailAddressProperty;
    @BindView(R.id.act_search_distance)
    TextView actSearchDistance;
    //    @BindView(R.id.act_search_goOrder)
//    TextView actSearchGoOrder;
    @BindView(R.id.act_search_location)
    TextView actSearchLocation;
    @BindView(R.id.act_search_call)
    ImageView actSearchCall;
    @BindView(R.id.title_body)
    TextView titleBody;
    @BindView(R.id.mainActivity_topbar_img)
    ImageView mainActivityTopbarImg;
    private String businessId;
    private DetailBusinessInfo detailBusinessInfo;
    private MyPagerAdapter adapter;
    private ImageView[] indicators;
    private String distance;
    private String[] aphotos;
    private long TIme = 2000;
    private ProgressDialog progressDialog;

    @Override
    protected void init() {
        super.init();
        businessId = getIntent().getStringExtra("packageName");
        distance = getIntent().getStringExtra("distance");
    }

    @Override
    protected void initViews() {
        super.initViews();
        setContentView(R.layout.activity_detail);
        ButterKnife.bind(this);
        StatusBarCompat.compat(this, getResources().getColor(R.color.green));
        titleBody.setText("商品详情");
        mainActivityTopbarImg.setVisibility(View.GONE);
    }

    @Override
    protected void initData() {
        super.initData();
        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("正在加载中...");
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.show();
        getBusinessInfo();
    }

    /**
     * 获取商户详情
     */
    private void getBusinessInfo() {
        BaseProtocal.builder(false).getBusinessInfo(new MyStringCallBack() {
            @Override
            public void onSuccess(String response) {
                PrintUtil.printRespones("商户详情", response);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String bi = jsonObject.optString("bi");
                    detailBusinessInfo = new Gson().fromJson(bi, DetailBusinessInfo.class);
                    if (detailBusinessInfo != null)
                        setpage();
                } catch (JSONException e) {

                }
            }

            @Override
            public void onFail(Exception e) {
                cancelDialog();
                ToastUtils.showToast("网络繁忙，请稍后重试");
            }
        }, businessId);
    }

    private void setpage() {
        cancelDialog();
        //        设置轮播大图
        setLargeImage();
        if (!TextUtils.isEmpty(detailBusinessInfo.pointsRatio))
            actDetailProfile.setText("消费送" + detailBusinessInfo.pointsRatio + "%兑换券");
        else
            actDetailProfile.setVisibility(View.GONE);
        actSearchName.setText(detailBusinessInfo.name);
        actDetailAddressProperty.setText(detailBusinessInfo.className + "/" + detailBusinessInfo.cityName + detailBusinessInfo.countryName);

        if (TextUtils.equals(distance, "0"))
            actSearchDistance.setVisibility(View.GONE);
        else
            actSearchDistance.setText("距离" + distance);
        if (!TextUtils.isEmpty(detailBusinessInfo.address))
            actSearchLocation.setText(detailBusinessInfo.address);
        if (!TextUtils.isEmpty(detailBusinessInfo.headPhoto) && !detailBusinessInfo.headPhoto.startsWith("null?")) {
            Glide.with(DetailActivity.this).load(detailBusinessInfo.headPhoto)
                    .override(140, 140)
                    .centerCrop()
                    .placeholder(R.drawable.pay_businessicon_defualt)
                    .error(R.drawable.pay_businessicon_defualt)
                    .into(actDetailSmallImg);
        }
    }

    private void setLargeImage() {
        aphotos = detailBusinessInfo.aPhoto.split("\\,");
        adapter = new MyPagerAdapter();
        largeImg.setAdapter(adapter);
        largeImg.addOnPageChangeListener(this);
        initIndicator(aphotos);
    }

    class MyPagerAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            return aphotos == null ? 0 : aphotos.length > 1 ? Integer.MAX_VALUE : aphotos.length;
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            View view = UIUtils.inflate(R.layout.item_grid);
            RecyclerImageView imageView = (RecyclerImageView) view.findViewById(R.id.image);
//            RecyclerImageView imageView = new RecyclerImageView(UIUtils.getContext());
//            imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
            if (!TextUtils.isEmpty(aphotos[position % aphotos.length]) && !aphotos[position % aphotos.length].startsWith("null?")) {
                PrintUtil.printRespones("商户图片地址;" + aphotos[position % aphotos.length]);
                Glide.with(DetailActivity.this).load(aphotos[position % aphotos.length])
//                查看大图时放弃使用内存缓存，图片从网络下载完成后会缓存到磁盘中，加载会从磁盘中加载，这样可以加速内存的回收
//                        .skipMemoryCache(true)
                        .placeholder(R.drawable.pay_businessicon_defualt)
                        .error(R.drawable.pay_businessicon_defualt)
                        .into(imageView);
            }
            container.addView(view);
            return view;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            if (object instanceof View) {
                RecyclerImageView imageView = (RecyclerImageView) ((View) object).findViewById(R.id.image);
                imageView.setImageBitmap(null);
            }
            container.removeView((View) object);
        }
    }

    /**
     * 初始化引导图标
     * 动态创建多个小圆点，然后组装到线性布局里
     *
     * @param aphotos
     */
    private void initIndicator(String[] aphotos) {
        AutoLinearLayout indicatorLayout = (AutoLinearLayout) findViewById(R.id.indicator);// 线性水平布局，负责动态调整导航图标
        indicators = new ImageView[aphotos.length];
        for (int i = 0; i < aphotos.length; i++) {
            // 循环加入指示器
            indicators[i] = new ImageView(UIUtils.getContext());
            indicators[i].setBackgroundResource(R.drawable.btn_circle_shape);
            if (i == 0) {
                indicators[i].setBackgroundResource(R.drawable.btn_circle_shape_r);
            }
            //指示点之间到间距
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(-2, -2);
            params.leftMargin = UIUtils.dip2px(5);
            indicatorLayout.addView(indicators[i], params);
        }
    }


    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
    }

    int index;

    @Override
    public void onPageSelected(int position) {
        for (int i = 0; i < indicators.length; i++) {
            if (i == position % aphotos.length)
                indicators[i].setBackgroundResource(R.drawable.btn_circle_shape_r);
            else
                indicators[i].setBackgroundResource(R.drawable.btn_circle_shape);
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {
    }

    @OnClick({R.id.act_search_call})
    public void onclick(View view) {
        switch (view.getId()) {
//            case R.id.act_search_goOrder:
////                下单
//                ToastUtils.showToast("去下单");
//                break;
            case R.id.act_search_call:
//                打电话给商家
                onCall();
                break;
        }
    }

    final public static int REQUEST_CODE_ASK_CALL_PHONE = 123;

    public void onCall() {
        AndPermission.with(this)
                .requestCode(REQUEST_CODE_ASK_CALL_PHONE)
                .permission(Manifest.permission.CALL_PHONE)
                .rationale(new RationaleListener() {
                    @Override
                    public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
                        AndPermission.rationaleDialog(DetailActivity.this, rationale);
                    }
                })
                .send();
    }

    @PermissionYes(REQUEST_CODE_ASK_CALL_PHONE)
    public void getCallPhoneSuccess(List<String> grantedPermissions) {
        callDirectly(detailBusinessInfo.phone);
    }

    @PermissionNo(REQUEST_CODE_ASK_CALL_PHONE)
    public void getCallPhoneFail(List<String> grantedPermissions) {
        if (AndPermission.hasAlwaysDeniedPermission(this, grantedPermissions)) {
            AndPermission.defaultSettingDialog(this, REQUEST_CODE_ASK_CALL_PHONE);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        AndPermission.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    private void callDirectly(String mobile) {
        Intent intent = new Intent();
        intent.setAction("android.intent.action.CALL");
        intent.setData(Uri.parse("tel:" + mobile));
        startActivity(intent);
    }

    /**
     * 取消对话框
     */
    private void cancelDialog() {
        if (progressDialog != null)
            progressDialog.dismiss();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        cancelDialog();
    }
}
